<template>
  <div>
    <h3 class="title">权限设置</h3>
    <ul v-loading="listLoading" class="treeMenu">
      <li class="tHead">
        <div>菜单</div>
        <div>功能权限按钮</div>
      </li>
      <li v-for="(item, index) in list" :key="item.id" class="tBody">
        <div>
          <div :style="{'background-color': showIndex === index ? '#f5f5f5': ''}" class="floor1" @click="floor1Handel(index)">
            <el-checkbox
              :indeterminate="item.isIndeterminate"
              v-model="item.checkAll"
              @change="checked => floorFrist(checked, item, index)">{{ item.name }}</el-checkbox>
            <span :class="[{'rotate90':rowIndex === index }, 'triangle']"/>
          </div>
          <div
            :ref="'fold'+index"
            :style="{height:(showIndex === index? arrH[index]+'px':contentH0)}"
            class="fold">
            <div v-for="data in item.children" :key="data.id">
              <div class="floor2">
                <el-checkbox
                  :indeterminate="data.isIndeterminate"
                  v-model="data.checkAll"
                  @change="checked => floorSecond(checked, data, item)">{{ data.name }}</el-checkbox>
              </div>
              <div class="floor3">
                <el-checkbox-group v-model="data.arrName" @change="checked => floorThrid(checked, data, item)">
                  <el-checkbox v-for="btn in data.children" :key="btn.id" :label="btn.name" @change="checked => changeIds(checked, btn.id)">{{ btn.name }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </div>
      </li>
    </ul>

    <!-- <table class="table">
      <thead>
        <tr>
          <td>菜单</td>
          <td>功能权限按钮</td>
        </tr>
      </thead>
      <tbody v-for="item in list" :key="item.id">
        <tr>
          <td>
            <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" @change="checked => floorFrist(checked, item)">{{ item.name }}</el-checkbox>
          </td>
          <td>&nbsp;</td>
        </tr>
        <tr v-for="data in item.children" :key="data.id">
          <td style="padding-left: 40px;">
            <el-checkbox
              :indeterminate="data.isIndeterminate"
              v-model="data.checkAll"
              @change="checked => floorSecond(checked, data, item)">{{ data.name }}</el-checkbox>
          </td>
          <td>
            <el-checkbox-group v-model="data.arrName" @change="checked => floorThrid(checked, data, item)">
              <el-checkbox v-for="btn in data.children" :key="btn.id" :label="btn.name" @change="checked => changeIds(checked, btn.id)">{{ btn.name }}</el-checkbox>
            </el-checkbox-group>
          </td>
        </tr>
      </tbody>
    </table> -->
    <div class="button_btns_box">
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button type="info" @click="$router.go(-1)">关闭</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionSetting, bindRolePermission } from '@/api/permission'
import { rolePermission, bindRole } from '@/api/sysRole'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      rowIndex: '',
      showIndex: -1,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      list: [],
      // defaultList: ['课程管理', '讲师管理', '订单管理', '报名管理', '佣金提现管理', '课程提现管理', '退佣金管理', '银行卡修改记录', '用户管理', '角色管理'],
      defaultList: [
        // '地推管理',
        // '会员管理',
        // '商品管理',
        // '商城轮播图',
        // '全部订单',
        // '未支付订单',
        // '已支付订单',
        // '商城订单管理',
        // '全部订单',
        // '未付款订单',
        // '已付款订单',
        // '已发货订单',
        // '已收货订单',
        // '已取消订单',
        // '发货地址管理',
        // '对公账号管理',
        // '平台抽佣设置',
        // '抽佣提现申请',
        // '佣金提现管理',
        // '平台抽佣提现管理',
        // '溯源环节模版',
        // '溯源商品',
        // '溯源标码',
        // '溯源商品批次',
        // '生成明细',
        // '发货地址',
        // '用户管理',
        // '角色管理',
        // '商品类型设置'
      ],
      subList: {
        rid: '',
        pidList: []
      },
      listLoading: false,
      arrH: [],
      contentH: '',
      contentH0: 'auto'
    }
  },
  watch: {
    'list'(val) {
      console.log(val)
      this.list = val
    }
  },
  created() {
    // alert(this.$route.query)
    // if (this.$route.query.rid === 'undefined') {
    //     this.$touer.push('/basic/role/list')
    // }
    // console.log('路由参数：', this.$route.query)
    const data = this.$route.query
    this.subList.rid = this.$route.query.rid
  },
  mounted() {
    this.getPermission()
  },
  methods: {
    getHeight() {
      this.listLoading = true
      this.contentH0 = 'auto'
      this.arrH = [];
      setTimeout(() => {
        this.list.forEach((item, index) => {
          this.arrH.push(this.$refs['fold' + index][0].clientHeight)
        })
        this.contentH0 = '0px'
        this.listLoading = false
      }, 1000)
    },
    floor1Handel(index) {
      if (this.showIndex === index) {
        this.showIndex = -1
        this.rowIndex = -1
      } else {
        this.showIndex = index
        this.rowIndex = index
      }
    },
    getPermission() {
      const data = this.$route.query
      rolePermission(data).then(res => {
        if (res.code === '200') {
          console.log(res)
          this.list = this.madeTableList(res.data)
          this.list = this.sortList(this.list)
          this.getHeight()
        } else {
          Message.error(res.message + '-' + res.data)
        }
        console.log(res)
      })
    },
    submitForm() {
      bindRole(this.subList).then(res => {
        if (Number(res.code) === 200) {
          Message.success('编辑成功')
          this.$router.go(-1);
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    },
    floorFrist(checked, data, index) {
      this.showIndex = index
      this.rowIndex = index
      // console.log(checked)
      console.log(data)
      const arr = []
      for (let i = 0; i < data.children.length; i++) {
        data.children[i].arrName = checked ? data.children[i].arrNames : []
        data.children[i].checkAll = checked
        data.children[i].isIndeterminate = false
        for (let j = 0; j < data.children[i].children.length; j++) {
          // data.children[i].arrName = this.pushNames(data.children[i].arrName, data.children[i].children[j].name)
          arr.push(data.children[i].children[j].id)
        }
      }
      data.isIndeterminate = false
      // console.log(arr)
      // if (data.name === '' || data.name === '基础数据管理' || data.name === '报名管理' || data.name === '订单管理' || data.name === '财务管理' || data.name === '基础设置') {
      if (data.name === '' ||
            data.name === '地推管理' ||
            data.name === '会员管理' ||
            data.name === '商品管理' ||
            data.name === '会员订单管理' ||
            data.name === '商城订单管理' ||
            data.name === '财务管理' ||
            data.name === '发货地址管理' ||
            data.name === '对公账号管理' ||
            data.name === '商品溯源管理' ||
            data.name === '权限管理' ||
            data.name === '平台抽佣' ||
            data.name === '酒店订单管理' ||
            data.name === '设置') {
        arr.push(data.id)
        // const dataArr = []
        for (let x = 0; x < data.children.length; x++) {
          arr.push(data.children[x].id)
          data.children[x].choose = checked
        }
        // console.log('arr', arr)
      }
      this.changeIds(checked, arr)
      console.log(this.subList.pidList.length)
    },
    floorSecond(checked, data, item) {
      console.log(item)
      console.log(data)
      item.isIndeterminate = false
      data.arrName = checked ? data.arrNames : []
      data.choose = checked
      data.isIndeterminate = false
      console.log('item.checkAll', item.checkAll)
      const arr = [] // 添加或者删除的id都放到arr里
      const dataNames = []
      for (let i = 0; i < data.children.length; i++) {
        arr.push(data.children[i].id)
      }
      if (arr.indexOf(data.id) === -1) arr.push(data.id)
      // if (arr.indexOf(item.id) === -1) arr.push(item.id)
      // if (checked) {
      //   if (arr.indexOf(data.id) === -1) arr.push(data.id)
      //   if (arr.indexOf(item.id) === -1) arr.push(item.id)
      // } else {
      //   for (let j = 0; j < arr.length; j++) {
      //     if (arr[j].id === data.id) {
      //       arr.splice(j, 1)
      //     }
      //   }
      // }
      if (checked) {
        if (arr.indexOf(item.id) === -1) arr.push(item.id)
      }
      for (let x = 0; x < item.children.length; x++) {
        if (item.children[x].choose) {
          dataNames.push('a')
        }
      }
      if (item.children.length === dataNames.length) {
        console.log('选择了所有')
        item.checkAll = true
      } else {
        item.checkAll = false
        item.isIndeterminate = true
      }
      if (!dataNames.length) { // 这个判断一定checked = false
        console.log('都没有选择', 'item的id是：', item.id)
        item.isIndeterminate = false
        if (arr.indexOf(item.id) === -1) arr.push(item.id)
      }
      this.changeIds(checked, arr)
      console.log(this.subList.pidList.length)
    },
    floorThrid(val, data, item) {
      const checkedCount = val.length
      data.checkAll = checkedCount === data.arrNames.length
      item.checkAll = checkedCount === data.arrNames.length
      data.isIndeterminate = checkedCount > 0 && checkedCount < data.arrNames.length
      item.isIndeterminate = checkedCount > 0 && checkedCount < data.arrNames.length
      // 控制一级菜单 和 二级菜单的是否存在
      if (!checkedCount) {
        data.isIndeterminate = true
        item.isIndeterminate = true
      }

      if (data.isIndeterminate || data.checkAll) {
        if (this.subList.pidList.indexOf(data.id) === -1) {
          this.subList.pidList.push(data.id)
        }
        console.log(data.name)
      }

      if (item.isIndeterminate || item.checkAll) {
        if (this.subList.pidList.indexOf(item.id) === -1) {
          this.subList.pidList.push(item.id)
        }
        // console.log(item.name)
      }
      console.log(this.subList.pidList.length)
      console.log('data', data)
    },
    changeIds(checked, arr) {
      console.log(checked)
      let newArr = []
      console.log(typeof (arr))
      if (typeof (arr) === 'number') {
        newArr.push(arr)
      } else {
        newArr = arr
      }
      // console.log(newArr.length, '个')
      let subArr = this.subList.pidList || []
      if (!subArr.length) subArr = newArr
      for (let i = 0; i < newArr.length; i++) {
        for (let j = 0; j < subArr.length; j++) {
          if (checked) { // 添加
            if (subArr.indexOf(newArr[i]) === -1) {
              subArr.push(newArr[i])
            }
          } else { // 删除
            if (subArr[j] === newArr[i]) {
              subArr.splice(j, 1)
            }
          }
        }
      }
      this.subList.pidList = subArr
    },
    pushNames(arrName, name) {
      const arr = []
      console.log('arrName::', arrName, 'name:', name)
      if (!arrName.length) {
        arr.push(name)
      }
      if (arrName.indexOf(name) === -1) {
        arr.push(name)
      }
      return arr
    },
    handleNodeClick(data) {
      console.log(data);
    },
    sortList(data) {
      // console.log(data)
      return data.sort((a, b) => a.index - b.index)
    },
    madeTableList(data) {
      const arr1 = []
      const arrId = []
      // const arr2 = []
      // const arr3 = []
      data.forEach((item) => {
        if (item.pid === 0) {
          let json = {}
          json = Object.assign({}, item)
          json.label = item.name
          json.checkAll = false
          json.isIndeterminate = false;
          // json.id = item.id
          if (item.name === '地推管理') json.index = 0
          if (item.name === '会员管理') json.index = 1
          if (item.name === '商品管理') json.index = 2
          if (item.name === '会员订单管理') json.index = 3
          if (item.name === '商城订单管理') json.index = 4
          if (item.name === '财务管理') json.index = 5
          if (item.name === '发货地址管理') json.index = 6
          if (item.name === '对公账号管理') json.index = 7
          if (item.name === '商品溯源管理') json.index = 8
          if (item.name === '权限管理') json.index = 9
          if (item.name === '设置') json.index = 10
          json.children = []
          if (item.rid !== null) {
            arrId.push(item.id)
            json.checkAll = true
          }
          arr1.push(json)
          console.log(arrId)
        }
      })
      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < arr1.length; j++) {
          if (data[i].pid === arr1[j].id) {
            // if (this.defaultList.indexOf(data[i].name) !== -1) {
            data[i].label = data[i].name
            data[i].children = []
            data[i].ids = []
            data[i].arrNames = []
            const arrName = []
            for (let x = 0; x < data.length; x++) {
              if (data[x].pid === data[i].id && data[x].name !== '下架' && data[x].name !== '停用') {
                // data[x].checked = false
                data[x].label = data[x].name
                if (data[x].name === '新增' || data[x].name === '详情') data[x].index = 0
                if (data[x].name === '查看' || data[x].name === '备注' || data[x].name === '提课程款') data[x].index = 1
                if (data[x].name === '编辑' || data[x].name === '审核' || data[x].name === '退佣金') data[x].index = 2
                if (data[x].name === '上架' || data[x].name === '启用' || data[x].name === '停用' || data[x].name === '驳回' || data[x].name === '权限设置' || data[x].name === '绑卡') data[x].index = 3
                if (data[x].name === '打款' || data[x].name === '停用') data[x].index = 4
                if (data[x].name === '查看备注') data[x].index = 5
                if (data[x].name === '上架') data[x].name = '上架/下架'
                if (data[x].name === '启用') data[x].name = '启用/停用'
                if (data[x].rid !== null) {
                  data[i].ids.push(data[x].id)
                  arrName.push(data[x].name)
                  arrId.push(data[x].id)
                }
                data[i].arrNames.push(data[x].name)
                data[i].children.push(data[x])
              }
            }
            data[i].children = this.sortList(data[i].children)
            data[i].checkAll = true;
            data[i].choose = true
            data[i].isIndeterminate = false;
            // data[i].arrNames = arrName
            data[i].arrName = arrName
            console.log(arrName)
            if (!arrName.length) {
              data[i].checkAll = false
              data[i].choose = false
            }
            console.log(arr1[j].checkAll)
            arr1[j].children.push(data[i])
            // arrId.push(data[i].id)
            // }
            if (data[i].rid !== null) arrId.push(data[i].id)
          }
        }
      }
      console.log(arr1)
      // console.log(arrId)
      this.subList.pidList = arrId
      return arr1
    }
  }
};
</script>
<style scoped>
  /*/deep/.el-tree-node__children .el-tree-node__content:nth-of-type(1){
    background: red;
  }*/
  /* /deep/.el-tree-node.is-expanded>.el-tree-node__children {
    background: yellow
  } */
  .title{
    line-height: 30px;
    margin-left: 20px;
  }
  .table{
    margin: 10px 0 0 20px;
    width: 1280px;
    border-left: 1px solid #DDD;
    border-top: 1px solid #DDD;
    border-collapse:collapse;
    border-spacing:0;
  }
  .table thead td{
    text-align: left;
    font-size: 14px;
    color: #333;
    font-weight: bold;
  }
  .table td{
    border-right: 1px solid #DDD;
    border-bottom: 1px solid #DDD;
    padding: 10px 20px;
  }
  .button_btns_box{
    width: 1100px;
    margin-top: 20px;
    text-align: center;
  }

  .el-checkbox+.el-checkbox{
      margin-left: 16px;
  }

 .el-checkbox__input.is-checked+.el-checkbox__label{
      padding-left: 6px;
  }

  .treeMenu{
      padding: 0;
      width: 1280px;
      border-left: 1px solid #ddd;
      border-top: 1px solid #ddd;
      margin-left: 20px;
      overflow: hidden;
      font-size: 14px;
  }
  .treeMenu li {
      width: 100%;
      overflow: hidden;
  }

  .treeMenu li div{
      box-sizing: border-box;
  }

  .treeMenu .tHead div{
      height: 40px;
      line-height: 40px;
      border-right: 1px solid #ddd;
      border-bottom: 1px solid #ddd;
      float: left;
      box-sizing: border-box;
       padding-left: 30px;
       font-weight: bold;
  }

  .treeMenu .tHead div:nth-last-of-type(1){
      width: 84%;

  }
  .treeMenu .tHead div:nth-last-of-type(2){
      width: 16%;
  }

  .tBody {
      overflow: hidden;
  }

  .floor1{
      width: 100%;
      height: 40px;
      line-height: 40px;
      border-right: 1px solid #ddd;
      border-bottom: 1px solid #ddd;
      padding-left: 10px;
  }

  .floor1:hover{
      background: #f0f0f0;
  }

  .fold{
      width: 100%;
      overflow: hidden;
      transition: all .2s;
  }
   .fold .el-checkbox__label{
      padding-left: 4px !important
  }

  .floor2, .floor3{
      float: left;
      height: 40px;
      line-height: 40px;
      border-right: 1px solid #ddd;
      border-bottom: 1px solid #ddd;
  }

  .fold .floor2 {
      padding-left: 30px;
      width:16%;
  }

  .fold .floor3 {
      width:84%;
      padding-left: 10px;
      font-size: 12px;
  }

  .fold .floor3 div{
      float: left;
      margin-right: 3px;
  }
  .titleBg{
      background-color: #f9f9f9;
  }

  .triangle{
        width:0;
        height:0;
        border-top:5px solid transparent;
        border-bottom:5px solid transparent;
        border-left:5px solid #409EFF;
        display: inline-block;
        transition: all .2s;
        margin-left: 10px;
    }

    .rotate90 {
        transform:rotate(90deg);
    }
</style>
